//
//  LQRegisterViewController.m
//  LQProductIntelligenceService
//
//  Created by Yim on 16/5/14.
//  Copyright © 2016年 张宁. All rights reserved.
//

#import "LQRegisterViewController.h"
#import "LQCompanyViewController.h"
#import "LQLoginViewController.h"
#import "HZQRegexTestter.h"
//#import <SMS_SDK/SMSSDK.h>
#import "AFNetworking.h"

@interface LQRegisterViewController ()<UIPopoverPresentationControllerDelegate,UITextFieldDelegate>
{
    NSNumber *_userRegister;
}
// 注册用户名
@property (weak, nonatomic) IBOutlet UITextField *registerUserNameField;
@property (weak, nonatomic) IBOutlet UITextField *registerUserPasswordField;

/** 注册手机号*/
@property (weak, nonatomic) IBOutlet UITextField *registerPhoneField;

@property (weak, nonatomic) IBOutlet UITextField *phoneVerityCodeField;

- (IBAction)clickRegisterBtn:(id)sender;

// 公司名视图
@property (nonatomic , strong) LQCompanyViewController *companyView;
// 提示label
@property (weak, nonatomic) IBOutlet UILabel *remindLabel;

@property (weak, nonatomic) IBOutlet UIView *baseView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topConstraint;
@property (weak, nonatomic) IBOutlet UIButton *registerFrameLineBtn;
@property (weak, nonatomic) IBOutlet UIView *remindView;
@property (weak, nonatomic) IBOutlet UIButton *verifyTimeBtn;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;

- (IBAction)getVerityCodeBtn:(UIButton *)sender;

@property(nonatomic)CGFloat initialTopConstant;

/**  *  公司类型数组    */
@property (nonatomic , strong) NSArray *companyTypes;

@property (nonatomic, strong) NSTimer* timer2;

@property (nonatomic, strong) NSTimer* timer1;

@end

static int count = 0;

@implementation LQRegisterViewController

static LQCompanyViewController *_companyView = nil;
- (LQCompanyViewController *)companyView
{
    if (_companyView == nil) {
        _companyView = [[LQCompanyViewController alloc] init];
    }
    return _companyView;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.initialTopConstant = self.topConstraint.constant;
    
    
    [self createBtn];
    
    self.timeLabel.hidden = YES;
   
    [_timer2 invalidate];
    [_timer1 invalidate];
     count = 0;
    
}


- (void) createBtn
{
    
    UIButton *button = [UIButton buttonWithBackAddTarget:self addAction:@selector(backVC)];
    [self.view addSubview:button];
    
}


#pragma mark - 和通知相关
- (void) listenNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(companyDidChange:) name:@"changeCompanyName" object:nil];
}
// 修改登录公司名并保存
- (void) companyDidChange:(NSNotification *)notification
{
    NSString *companyName = notification.userInfo[@"companyName"];
    self.companyName = companyName;
   
    
}

- (void) backVC
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self settingsFieldLeftView];

}
- (void) settingsFieldLeftView
{
    // 给Filed设置左边视图
    UIImage *imageN = [UIImage imageNamed:@"icon"];
    UIImageView *leftVN = [[UIImageView alloc]initWithImage:imageN];
    leftVN.contentMode = UIViewContentModeCenter;
    leftVN.frame = CGRectMake(0, 0, 50, 20);
    self.registerUserNameField.leftViewMode = UITextFieldViewModeAlways;
    self.registerUserNameField.leftView = leftVN;
    
    // 给Filed设置左边视图
    UIImage *imageL = [UIImage imageNamed:@"lock"];
    UIImageView *leftVL = [[UIImageView alloc]initWithImage:imageL];
    leftVL.contentMode = UIViewContentModeCenter;
    leftVL.frame = CGRectMake(0, 0, 50, 20);
    self.registerUserPasswordField.leftViewMode = UITextFieldViewModeAlways;
    self.registerUserPasswordField.leftView = leftVL;
    
//    [self.registerPhoneField setTextFieldLeftView:@"phone"];
    // 给Filed设置左边视图
    UIImage *imageP = [UIImage imageNamed:@"phone"];
    UIImageView *leftVP = [[UIImageView alloc]initWithImage:imageP];
    leftVP.contentMode = UIViewContentModeCenter;
    leftVP.frame = CGRectMake(0, 0, 50, 20);
    self.registerPhoneField.leftViewMode = UITextFieldViewModeAlways;
    self.registerPhoneField.leftView = leftVP;
    
//    [self.phoneVerityCodeField setTextFieldLeftView:@"verifycode"];
    // 给Filed设置左边视图
    UIImage *imageV = [UIImage imageNamed:@"verifycode"];
    UIImageView *leftVV = [[UIImageView alloc]initWithImage:imageV];
    leftVV.contentMode = UIViewContentModeCenter;
    leftVV.frame = CGRectMake(0, 0, 50, 20);
    self.phoneVerityCodeField.leftViewMode = UITextFieldViewModeAlways;
    self.phoneVerityCodeField.leftView = leftVV;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == self.registerUserNameField) {
        
        [self.registerUserPasswordField becomeFirstResponder];
        
    }else if (textField == self.registerUserPasswordField)
    {
        [self.phoneVerityCodeField becomeFirstResponder];
    }else if (textField == self.registerPhoneField)
    {
        [self.phoneVerityCodeField becomeFirstResponder];
    }else if (textField == self.phoneVerityCodeField)
    {
        [self.view endEditing:YES];
        [self clickRegisterBtn:nil];
    }
    return YES;
}




- (IBAction)clickRegisterBtn:(id)sender {
    self.registerFrameLineBtn.selected = !self.registerFrameLineBtn.selected;
    BOOL nameIsSuccess;
    nameIsSuccess = [HZQRegexTestter validateStrWithRange:@"{1,20}" str:self.registerUserNameField.text];
    
    if (!nameIsSuccess) {
//       [SVProgressHUD showErrorWithStatus:@"请输入用户名" withDuration:1.5f];
        self.remindLabel.text = @"用户名不能为空";
        [self remindAnimationResult];
        [self.registerUserNameField becomeFirstResponder];
        return;
    }else{
        [self verifyUserNameIsExist];
    }
}

- (void) judgeInputIsTrue
{
    BOOL passwordIsSuccess;
    passwordIsSuccess = [HZQRegexTestter validateStrWithRange:@"{6,20}" str:self.registerUserPasswordField.text];
//    BOOL emailIsSuccess;
//    emailIsSuccess = [HZQRegexTestter validateEmail:@"text@163.c9m"];
    BOOL phoneIsSuccess;
    phoneIsSuccess = [HZQRegexTestter validatePhone:self.registerPhoneField.text];
    
    if (!passwordIsSuccess)
    {
        self.remindLabel.text = @"密码不能为空长度不能低于6位";
        [self remindAnimationResult];
        [self.registerUserPasswordField becomeFirstResponder];
        return;
    }else if (!phoneIsSuccess)
    {
        //        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号" withDuration:1.5f];
        self.remindLabel.text = @"请输入正确的手机号";
        [self remindAnimationResult];
        [self.registerPhoneField becomeFirstResponder];
        return;
    } else if (self.phoneVerityCodeField.text.length != 6)
    {
        //        [SVProgressHUD showErrorWithStatus:@"请输入正确的验证码" withDuration:1.5f];
        self.remindLabel.text = @"验证码输入错误!";
        [self remindAnimationResult];
        [self.phoneVerityCodeField becomeFirstResponder];
        return;
    }else
    {
        
        /*
        [SMSSDK commitVerificationCode:self.phoneVerityCodeField.text phoneNumber:self.registerPhoneField.text zone:@"86" result:^(NSError *error) {
            if (error) {
                MYLog(@"error = %@",error);
                [MBProgressHUD showError:@"验证码输入错误!"];
            }else{
                MYLog(@"验证成功");
                // 注册账号
                [self loadRegisterInfoToServer];
                
            }
        }];
         */
    }
}

#pragma mark - 和网络相关
- (void) verifyUserNameIsExist
{
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"userName"] = self.registerUserNameField.text;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    /*
    [manager POST:USERNAMEISEXIST parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        BOOL exist = [string boolValue];
        MYLog(@"success = %i",exist);
        if (exist) {
            [self judgeInputIsTrue];
        }else
        {
            [MBProgressHUD showError:@"用户名已经存在!"];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        MYLog(@"error = %@",error);
        [MBProgressHUD showError:@"连接失败!"];
    }];
     */
    
}


- (void) remindAnimationResult
{
    self.remindView.hidden = NO;
    CGFloat distance =  70;
    self.topConstraint.constant = distance;
    
    [UIView animateWithDuration:0.1 animations:^{
        [self.view layoutIfNeeded];
    }];
    if (self.registerFrameLineBtn.selected) {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.baseView.center;
            point.x += 3;
            [self.baseView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }else
    {
        [UIView animateWithDuration:1.0 delay:0.0 usingSpringWithDamping:0.0 initialSpringVelocity:5.0 options:UIViewAnimationOptionCurveEaseIn animations:^{
            CGPoint point = self.baseView.center;
            point.x -= 3;
            [self.baseView setCenter:point];
        } completion:nil];
        [self recoverRemindView];
    }
}
/**
 *  收回View
 */
- (void) recoverRemindView
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                self.remindView.hidden = YES;
                CGFloat distance =  self.initialTopConstant;
                self.topConstraint.constant = distance;
                [UIView animateWithDuration:0.1 animations:^{
                    [self.view layoutIfNeeded];
                }];
            });
        });
    });
}



- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
#pragma mark - UIPopoverPresentationControllerDelegate
- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller traitCollection:(UITraitCollection *)traitCollection
{
    return UIModalPresentationNone;
}

- (IBAction)getVerityCodeBtn:(UIButton *)sender
{
    BOOL isSuccess;
    isSuccess = [HZQRegexTestter validatePhone:self.registerPhoneField.text];
    
    if (isSuccess) {
        self.timeLabel.text = @"剩余60秒";
        [_timer2 invalidate];
        [_timer1 invalidate];
        
        count = 0;
        
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES];
        NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
        _timer1 = timer;
        _timer2 = timer2;
        
        self.timeLabel.hidden = NO;
        self.verifyTimeBtn.hidden = YES;
        
        /*
        
        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.registerPhoneField.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
            if (error) {
                MYLog(@"error = %@",error);
            [SVProgressHUD showErrorWithStatus:@"验证码获取失败"];
           [self.verifyTimeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
            }else{
                MYLog(@"验证码发送成功");
                self.timeLabel.text = @"剩余60秒";
                [_timer2 invalidate];
                [_timer1 invalidate];
                
                count = 0;
                
                NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(showRepeatButton) userInfo:nil repeats:YES];
                NSTimer *timer2 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];
                _timer1 = timer;
                _timer2 = timer2;
                
                self.timeLabel.hidden = NO;
                self.verifyTimeBtn.hidden = YES;
               
            }
        }];
         */
    }else
    {
        UIAlertController *alert = [UIAlertController alertWithTitle:@"提示" alertStyle:UIAlertControllerStyleAlert contentString:@"请输入手机号" andWithCancel:@"确定"];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
         
    
}
- (void) showRepeatButton
{
    self.timeLabel.hidden = YES;
    self.verifyTimeBtn.hidden = NO;
    [self.verifyTimeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
    [_timer1 invalidate];
    return;
}

- (void) updateTime
{
    count++;
    if (count >= 60) {
        [_timer2 invalidate];
        return;
    }
    self.timeLabel.text = [NSString stringWithFormat:@"剩余%i秒",60 - count];
}

- (void)dealloc
{
    [_timer1 invalidate];
    [_timer2 invalidate];
    _timer1 = nil;
    _timer2 = nil;
}
@end
